# serializers.py

from rest_framework import serializers
from .models import BayInformation

class BayInformationSerializer(serializers.ModelSerializer):
    class Meta:
        model = BayInformation
        fields = '__all__'

    def create(self, validated_data):
        return BayInformation.objects.create(**validated_data)


class BayInformationImportSerializer(serializers.Serializer):
    """
    专用于 Excel 导入的数据校验和转换
    不包含 bay_id（因为导入时不需要提供ID）
    """

    first_level_area = serializers.CharField(max_length=100)
    second_level_area = serializers.CharField(max_length=100)
    bay_number = serializers.CharField(max_length=50)
    bay_description = serializers.CharField(allow_blank=True, required=False)
    dimension = serializers.CharField(allow_blank=True, required=False)
    lifting_capacity = serializers.DecimalField(max_digits=10, decimal_places=2, required=False)
    height_limit = serializers.DecimalField(max_digits=10, decimal_places=2, required=False)
    labor_team = serializers.CharField(allow_blank=True, required=False)
    designated_segment = serializers.CharField(max_length=50, allow_blank=True, required=False)
    segment_type = serializers.CharField(max_length=100, allow_blank=True, required=False)
    attribute = serializers.CharField(allow_blank=True, required=False)

    def validate_bay_number(self, value):
        if not value.strip():
            raise serializers.ValidationError("胎位编号不能为空")
        return value

    def validate_first_level_area(self, value):
        if not value.strip():
            raise serializers.ValidationError("一级区域不能为空")
        return value

    def validate_second_level_area(self, value):
        if not value.strip():
            raise serializers.ValidationError("二级区域不能为空")
        return value

    def create(self, validated_data):
        return BayInformation(**validated_data)

    def update(self, instance, validated_data):
        for key, value in validated_data.items():
            setattr(instance, key, value)
        return instance